import { http } from '@/utils/request'
import type { 
  ApiResponse,
  Question,
  QuestionFilters,
  PaginationResult,
  Tag,
  Submission,
  SubmissionResult,
  ProgrammingLanguage
} from '@/types'

/**
 * 题目API
 */
export const questionApi = {
  // 获取题目列表
  getQuestions(filters: QuestionFilters): Promise<ApiResponse<PaginationResult<Question>>> {
    return http.post('/v1/Getquestion', filters)
  },

  // 获取题目列表（GET方式，兼容查询参数）
  getQuestionsWithParams(params: {
    page?: number
    page_size?: number
    tags?: string
    difficulty?: string
    status?: string
    search?: string
  } = {}): Promise<ApiResponse<PaginationResult<Question>>> {
    // 将逗号分隔的字符串转换为数组
    const processedParams = {
      ...params,
      tags: params.tags ? params.tags.split(',') : undefined,
      difficulty: params.difficulty ? params.difficulty.split(',') : undefined,
      status: params.status ? params.status.split(',') : undefined,
    }
    return http.get('/v1/questions/', { params: processedParams })
  },

  // 获取题目详情
  getQuestion(questionId: number): Promise<ApiResponse<Question>> {
    return http.get(`/v1/questions/${questionId}`)
  },

  // 创建题目（教师和管理员权限）
  createQuestion(data: {
    title: string
    content: string
    input_format?: string
    output_format?: string
    constraints?: string
    sample_input?: string
    sample_output?: string
    difficulty: 'Easy' | 'Medium' | 'Hard'
    time_limit?: number
    memory_limit?: number
    source?: string
    tag_ids?: number[]
    basecode?: Record<string, string>
    run_code?: Record<string, string>
  }): Promise<ApiResponse<{ id: number }>> {
    return http.post('/v1/questions/create', data)
  },

  // 更新题目（教师和管理员权限）
  updateQuestion(questionId: number, data: {
    title?: string
    content?: string
    input_format?: string
    output_format?: string
    constraints?: string
    sample_input?: string
    sample_output?: string
    difficulty?: 'Easy' | 'Medium' | 'Hard'
    time_limit?: number
    memory_limit?: number
    source?: string
    tag_ids?: number[]
    status?: 'draft' | 'published' | 'archived'
    basecode?: Record<string, string>
    run_code?: Record<string, string>
  }): Promise<ApiResponse<void>> {
    return http.put(`/v1/questions/${questionId}`, data)
  },

  // 删除题目（管理员权限）
  deleteQuestion(questionId: number): Promise<ApiResponse<void>> {
    return http.delete(`/v1/questions/${questionId}`)
  },

  // 提交代码
  submitCode(data: {
    question_id: number
    language: ProgrammingLanguage
    code: string
  }): Promise<ApiResponse<SubmissionResult>> {
    return http.post('/v1/submissions', data)
  },

  // 获取提交详情
  getSubmission(submissionId: number): Promise<ApiResponse<Submission & {
    judge_result?: {
      test_cases: Array<{
        id: number
        status: string
        execution_time: number
        memory_used: number
        input?: string
        output?: string
        expected?: string
        error_message?: string
      }>
      summary: {
        total_test_cases: number
        passed_test_cases: number
        max_execution_time: number
        max_memory_used: number
      }
    }
  }>> {
    return http.get(`/v1/submissions/${submissionId}`)
  },

  // 获取题目提交记录
  getQuestionSubmissions(questionId: number, params: {
    page?: number
    page_size?: number
    language?: ProgrammingLanguage
    status?: string
    user_id?: number
  } = {}): Promise<ApiResponse<PaginationResult<Submission>>> {
    return http.get(`/v1/questions/${questionId}/submissions`, { params })
  },

  // 收藏题目
  favoriteQuestion(questionId: number): Promise<ApiResponse<void>> {
    return http.post(`/v1/questions/${questionId}/favorite`)
  },

  // 取消收藏题目
  unfavoriteQuestion(questionId: number): Promise<ApiResponse<void>> {
    return http.delete(`/v1/questions/${questionId}/favorite`)
  },

  // 获取用户收藏的题目
  getFavoriteQuestions(params: {
    page?: number
    page_size?: number
  } = {}): Promise<ApiResponse<PaginationResult<Question>>> {
    return http.get('/v1/questions/favorites', { params })
  },

  // 点赞题目
  likeQuestion(questionId: number): Promise<ApiResponse<void>> {
    return http.post(`/v1/questions/${questionId}/like`)
  },

  // 取消点赞题目
  unlikeQuestion(questionId: number): Promise<ApiResponse<void>> {
    return http.delete(`/v1/questions/${questionId}/like`)
  },

  // 获取题目统计信息
  getQuestionStats(questionId: number): Promise<ApiResponse<{
    total_submissions: number
    accepted_submissions: number
    acceptance_rate: number
    difficulty_distribution: {
      easy: number
      medium: number
      hard: number
    }
    language_distribution: Record<ProgrammingLanguage, number>
    avg_execution_time: number
    avg_memory_used: number
  }>> {
    return http.get(`/v1/questions/${questionId}/stats`)
  },

  // 获取题目解题报告
  getQuestionSolution(questionId: number): Promise<ApiResponse<{
    content: string
    author: {
      id: number
      username: string
      avatar_url: string
    }
    created_at: string
    updated_at: string
  }>> {
    return http.get(`/v1/questions/${questionId}/solution`)
  },

  // 获取题目讨论
  getQuestionDiscussions(questionId: number, params: {
    page?: number
    page_size?: number
    sort?: 'latest' | 'popular' | 'oldest'
  } = {}): Promise<ApiResponse<PaginationResult<{
    id: number
    title: string
    content: string
    author: {
      id: number
      username: string
      avatar_url: string
    }
    reply_count: number
    like_count: number
    created_at: string
    updated_at: string
  }>>> {
    return http.get(`/v1/questions/${questionId}/discussions`, { params })
  },

  // 搜索题目
  searchQuestions(params: {
    keyword: string
    page?: number
    page_size?: number
    tags?: string[]
    difficulty?: string[]
  }): Promise<ApiResponse<PaginationResult<Question>>> {
    return http.get('/v1/questions/search', { params })
  },

  // 获取推荐题目
  getRecommendedQuestions(params: {
    count?: number
    difficulty?: 'Easy' | 'Medium' | 'Hard'
    tags?: string[]
  } = {}): Promise<ApiResponse<Question[]>> {
    return http.get('/v1/questions/recommended', { params })
  },

  // 获取今日推荐题目
  getDailyQuestion(): Promise<ApiResponse<Question>> {
    return http.get('/v1/questions/daily')
  },

  // 获取题目标签
  getTags(): Promise<ApiResponse<Tag[]>> {
    return http.get('/v1/tags')
  },

  // 创建题目标签（管理员权限）
  createTag(data: {
    name: string
    display_name: string
    color?: string
    description?: string
  }): Promise<ApiResponse<{ id: number }>> {
    return http.post('/v1/tags', data)
  },

  // 更新题目标签（管理员权限）
  updateTag(tagId: number, data: {
    name?: string
    display_name?: string
    color?: string
    description?: string
  }): Promise<ApiResponse<void>> {
    return http.put(`/v1/tags/${tagId}`, data)
  },

  // 删除题目标签（管理员权限）
  deleteTag(tagId: number): Promise<ApiResponse<void>> {
    return http.delete(`/v1/tags/${tagId}`)
  },

  getQuestionById(id: number): Promise<ApiResponse<Question>> {
    return http.get(`/v1/questions/${id}`)
  },

  // 获取全局题目统计信息
  getGlobalQuestionStats(): Promise<ApiResponse<{
    total_questions: number,
    difficulty_stats: {
      easy: number,
      medium: number,
      hard: number
    },
    popular_questions: number
  }>> {
    return http.get('/v1/questions/stats')
  },
}


